﻿//Constant
var pageSize = 10;
var currentPageIndex = 1;
var indexSize = 3;
var currentIndexIndex = 1;
var maxIndexIndex = 1;

// Utility

Array.prototype.del=function(n) { //n表示第几项，从0开始算起。
//prototype为对象原型，注意这里为对象增加自定义方法的方法。
if(n<0) //如果n<0，则不进行任何操作。
    return this;
else
    return this.slice(0,n).concat(this.slice(n+1,this.length));
    /*
      concat方法：返回一个新数组，这个新数组是由两个或更多数组组合而成的。
      　　　　　　这里就是返回this.slice(0,n)/this.slice(n+1,this.length)
     　　　　　　组成的新数组，这中间，刚好少了第n项。
      slice方法： 返回一个数组的一段，两个参数，分别指定开始和结束的位置。
    */
}

Array.prototype.delStr=function(str) 
{ 
    for(var i=0;i<this.length;i++)
    {
        if(this[i]==str)
        {
            return this.del(i);
        }
    }
    
    return this;
}


function getSubstr(str, sign)
{
    var ret = "";
    if(str.indexOf(sign)<=0)
    {
        ret = str;
    }
    else
    {
        ret = str.substr(0,str.indexOf(sign));
    }
    
    return ret;
}

String.prototype.trim=function() 
{ 
	return this.replace(/(\s*$)|(^\s*)/g, '');
}

//使用$get替代 by LanceZhang 2009.4.15
function $(id)
{
	return document.getElementById(id);
}
function $T(id)
{
	return document.getElementById(id).value.trim();
}
String.format = function()
{

    if( arguments.length == 0 )
    {
        return null; 
    }
    
    var str = arguments[0]; 

    for(var i=1;i<arguments.length;i++)
    {

        var re = new RegExp('\\{' + (i-1) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}

function StrToList(str, splitor)
{
    return str.split(splitor);
}

function tabSelectChange(tabIdList, selectedId)
{
    for(var i=0;i<tabIdList.length;i++)
    {
        if(tabIdList[i].ID == selectedId)
        {
            document.getElementById(tabIdList[i].Ctl).className = "tab_select";
            document.getElementById(tabIdList[i].ID).style.display = "block";
        }
        else
        {

            document.getElementById(tabIdList[i].Ctl).className = "tab_notselect";
            document.getElementById(tabIdList[i].ID).style.display = "none";
        }
    }
    
    return false;
}

function GetRequestParam()
{ 
    var request = new Object();
    var id=location.search.substring(1); 
    if(id=="")
        return null;
    var tmp=id.split("&"); 
    var tmp_l=tmp.length; 

    for(var i=0;i<tmp_l;i++)
    { 
        var tmp2=tmp[i]; 
        tmp2=tmp2.split("="); 
        request[tmp2[0]] = tmp2[1];
    } 
    return request; 
} 

function setCookie (name, value, days) {
  var expires = new Date();
  expires.setTime (expires.getTime() + (86400 * 1000 * days));
  document.cookie = name + "=" + escape(value) +   "; expires=" + expires.toGMTString() +  "; path=/";
}

function getCookie(name) {
  var search;
  search = name + "="
  offset = document.cookie.indexOf(search) 
  if (offset != -1) {
    offset += search.length ;
    end = document.cookie.indexOf(";", offset) ;
    if (end == -1)
      end = document.cookie.length;
    return unescape(document.cookie.substring(offset, end));
  }
  else
    return "";
}

function deleteCookie(name) {
  var expdate = new Date();
  expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
  setCookie(name, "", expdate);
}

function IsLogin()
{
    try
    {
        WSLogin.IsLogin(OnCompleteIsLogin, OnTimeOut, OnError);
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteIsLogin(args)
    {
        if(args)
        {

        }
        else
        {
            alert("请先登陆");
        }
    }
}

// Utility end

// Open dialog
function alertWin(closeBtnId, openDivId,titleId, w, h){ 
    var titleheight = "22px"; // 提示窗口标题高度 
    var bordercolor = "#666699"; // 提示窗口的边框颜色 
    var titlecolor = "#FFFFFF"; // 提示窗口的标题颜色 
    var titlebgcolor = "#666699"; // 提示窗口的标题背景色
    var bgcolor = "#FFFFFF"; // 提示内容的背景色
    
    var iWidth = document.body.clientWidth; 
    var iHeight = document.documentElement.clientHeight; 
    
    var bgObj = document.createElement("div"); 
    bgObj.style.cssText = "position:absolute;left:0px;top:0px;width:"+iWidth+"px;height:"+Math.max(document.forms[0].clientHeight, document.body.clientHeight)+"px;filter:Alpha(Opacity=30);opacity:0.3;background-color:#000000;z-index:101;";
//    document.body.appendChild(bgObj)
    document.forms[0].appendChild(bgObj); 
    var msgObj=document.createElement("div");
    msgObj.style.cssText = "position:absolute;font:11px '宋体';top:"+(iHeight-h)/2+"px;left:"+(iWidth-w)/2+"px;width:"+w+"px;height:"+h+"px;border:1px solid "+bordercolor+";background-color:"+bgcolor+";padding:1px;line-height:22px;z-index:102;";
    document.forms[0].appendChild(msgObj);
    
    
    // append reg box to added div
    var regBox = document.getElementById(openDivId);
    regBox.style.display = "block";
    msgObj.appendChild(regBox);
    
        document.getElementById(closeBtnId).onclick = function()
        { 
            try
            {
                document.forms[0].removeChild(msgObj); 
                document.forms[0].removeChild(bgObj); 
                document.forms[0].appendChild(regBox);
                regBox.style.display = "none";
            }
            catch(e)
            {}
            return false;
        } 
        var completeTripAdd = document.getElementById("completeTripAdd");
        if(completeTripAdd)
        {
            completeTripAdd.onclick = function()
            {
                GetTrips(requestParam.ehId);
                document.forms[0].removeChild(msgObj); 
                document.forms[0].removeChild(bgObj); 
                document.forms[0].appendChild(regBox);
                regBox.style.display = "none";
                return false;
            }
        }
    
//    var table = document.createElement("table");
//    msgObj.appendChild(table);    
//    table.style.cssText = "margin:0px;border:0px;padding:0px;";
//    table.cellSpacing = 0;
//    var tr = table.insertRow(-1);
//    var titleBar = tr.insertCell(-1);
//    titleBar.style.cssText = "width:100%;height:"+titleheight+"px;text-align:left;padding:3px;margin:0px;font:bold 13px '宋体';color:"+titlecolor+";border:1px solid " + bordercolor + ";cursor:move;background-color:" + titlebgcolor;
//    titleBar.style.paddingLeft = "10px";
//    titleBar.innerHTML = title;
    var moveX = 0;
    var moveY = 0;
    var moveTop = 0;
    var moveLeft = 0;
    var moveable = false;
    var docMouseMoveEvent = document.onmousemove;
    var docMouseUpEvent = document.onmouseup;
    
    //titleBar.onmousedown = function() {
    document.getElementById(titleId).onmousedown = function() {
        var evt = getEvent();
        moveable = true; 
        moveX = evt.clientX;
        moveY = evt.clientY;
        moveTop = parseInt(msgObj.style.top);
        moveLeft = parseInt(msgObj.style.left);
        
        document.onmousemove = function() {
            if (moveable) {
                var evt = getEvent();
                var x = moveLeft + evt.clientX - moveX;
                var y = moveTop + evt.clientY - moveY;
                if ( x > 0 &&( x + w < iWidth) && y > 0 && (y + h < iHeight) ) {
                    msgObj.style.left = x + "px";
                    msgObj.style.top = y + "px";
                }
            }    
        };
        document.onmouseup = function () { 
            if (moveable) { 
                document.onmousemove = docMouseMoveEvent;
                document.onmouseup = docMouseUpEvent;
                moveable = false; 
                moveX = 0;
                moveY = 0;
                moveTop = 0;
                moveLeft = 0;
            } 
        };
    }
    
    // 获得事件Event对象，用于兼容IE和FireFox
    function getEvent() {
        return window.event || arguments.callee.caller.arguments[0];
    }
} 
// end open div pannel

// login start
function Login()
{
    var ret = false;
    var emailAddress = "";
    var pwd = "";
    try
    {
        var loginErrorPanel = "loginErrorPanel";
        if(regularExpressionValid('loginEmail',EMAIL_REGULAR_EXPRESSION,loginErrorPanel,'Email 输入有误!')&&
           regularExpressionValid('loginPwd',PASSWORD_REGULAR_EXPRESSION,loginErrorPanel,'密码 输入有误!'))
        {
            emailAddress = document.getElementById('loginEmail').value;
            pwd = document.getElementById('loginPwd').value;
        
            var userProfile = {"Email":emailAddress,"Pwd":pwd};

            WSLogin.Login(userProfile, OnCompleteLogin, OnTimeOut, OnError);
            ret = true;
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
        ret = false;
    }
    
    function OnCompleteLogin(args)
    {
        if(!args.Ret)
        {
            var objSpan = $get("loginErrorPanel");
            objSpan.innerHTML = "登陆失败！";
            objSpan.style.display = "block";
        }
        else
        {
            if($get("cbkAutoLogin").checked)
            {
                setCookie("LU",emailAddress, 30);
            }
            document.getElementById("closeSignBtn").click();
            
            //after login, the href will go to home.aspx if the current page is index page
            if(window.location.href.indexOf("index.aspx")>=0)
            {
                window.location.href = args.Url;
            }
            else
            {
                window.location.href = getSubstr( window.location.href,"#");
            }
        }
    }
    
    return ret;
}
// login end

// login out
function Logout()
{
    var ret = false;
    try
    {
        WSLogin.Logout(OnCompleteLogout, OnTimeOut, OnError);
        ret = true;
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
        ret = false;
    }
    
    function OnCompleteLogout(args)
    {
        if(!args.Ret)
        {
            alert("failed");
        }
        else
        {
            deleteCookie("LU");
            window.location.href = args.Url;
        }
    }
    
    return ret;
}
// logout end

//User reg, used by registerbox only
function SaveReg()
{
    var ret = false;
    
    //不遵守,无法注册
    if(!$get("cbkConfirmLaw").checked)
        return false;
        
    var errorPanel = "error_panel";
    
    try
    {
        
        if(regularExpressionValid('txtEmailAddressReg',EMAIL_REGULAR_EXPRESSION,errorPanel,'Email 输入有误!')&&
           regularExpressionValid('NickNameReg',NICKNAME_REGULAR_EXPRESSION,errorPanel,'呢称 输入有误!')&&
           regularExpressionValid('password',PASSWORD_REGULAR_EXPRESSION,errorPanel,'密码 输入有误!'))
        {
            var emailAddress = document.getElementById('txtEmailAddressReg').value;
            var pwd = document.getElementById('password').value;
            var confirmPwd = document.getElementById('confirmpassword').value;
            var ProvinceID = document.getElementById('listProvinceHead').value;
            var CityID = document.getElementById('listCityHead').value;
            if(pwd != confirmPwd)
            {
                alert("两次密码输入的不同！");
                return;
            }
            
            var nickName=document.getElementById('NickNameReg').value;
            
            var userProfile = {"Nick_Name":nickName,"Email":emailAddress,"Pwd":pwd,"ProvinceID":ProvinceID,"CityID":CityID};
        
            WSLogin.SaveReg(userProfile, OnCompleteSaveReg, OnTimeOut, OnError);
            ret = true;
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
        ret = false;
    }
    
    function OnCompleteSaveReg(args) 
    {
        if(args.Ret)
        {
            window.location.href="register_step1.aspx";
        }
        else
        {
            var objSpan = $get(errorPanel);
            objSpan.style.display = "block";
            objSpan.innerHTML = "";
            if(args.RegResult == 0)
            {
                objSpan.innerHTML = "该Email已存在,请换一个";
            }
            else if(args.RegResult == 1)
            {
                objSpan.innerHTML = "该昵称已存在,请换一个";
            }
        }
     }

    
    return ret;
}


 
 function OnError(args) {
    alert("Error calling service method.");
}

function OnTimeOut(args) {
     //var message = error.get_message();
//              alert("1.time");
     alert('An unhandled exception has occurred:\n' + args);
}

//Show Province
function GetProvince(listProvinceId, listCityId)
{
    try
    {
        WSLogin.GetAllProvince(OnCompleteGetProvince, OnTimeOut, OnError);
     }
     catch(ex)
     {
        alert(ex.message);
     }
     
    function OnCompleteGetProvince(args)
    {
        var listProvince = document.getElementById(listProvinceId);
        for(var i=0;i<args.Provinces.length;i++)
        {
            var option = new Option(args.Provinces[i].Name,args.Provinces[i].ID);
            listProvince.add(option);
        }
        
        listProvince.onchange = function()
        {
            listProvinceChangeHandle();
        }

        listProvinceChangeHandle();
    }
    function listProvinceChangeHandle()
    {
        var listProvince = document.getElementById(listProvinceId);
        // fill city list
        SelectCityByProvinceId(listProvince.options[listProvince.selectedIndex].value, listCityId);
    }
}


// show province end

//Show cities
function SelectCityByProvinceId(pId, listCityId)
{
    try
    {
        WSLogin.SelectCityByProvinceId(pId,OnCompleteGetCity, OnTimeOut, OnError);
     }
     catch(ex)
     {
        alert(ex.message);
     }
     
    function OnCompleteGetCity(args)
    {
        var listCity = document.getElementById(listCityId);
        
        listCity.options.length=0;
        for(var i=0;i<args.ObjList.length;i++)
        {
            var option = new Option(args.ObjList[i].Name,args.ObjList[i].ID);
            listCity.add(option);
        }
    }
}
// show province end

//Show home Province
function GetHomeProvince()
{
    try
    {
        WSLogin.GetAllProvince(OnCompleteGetHomeProvince, OnTimeOut, OnError);
     }
     catch(ex)
     {
        alert(ex.message);
     }
}

function OnCompleteGetHomeProvince(args)
{
    var listProvince = document.getElementById("listHomeProvince");
    for(var i=0;i<args.Provinces.length;i++)
    {
        var option = new Option(args.Provinces[i].Name,args.Provinces[i].ID);
        listProvince.add(option);
    }
    
    listProvince.onchange = function()
    {
        listHomeProvinceChangeHandle();
    }

    listHomeProvinceChangeHandle();
}

function listHomeProvinceChangeHandle()
{
    var listProvince = document.getElementById("listHomeProvince");
//    var selectedOption = 
//        new Option(listProvince.options[listProvince.selectedIndex].text,
//                   listProvince.options[listProvince.selectedIndex].value);
    // fill city list
    SelectHomeCityByProvinceId(listProvince.options[listProvince.selectedIndex].value);
}

// show home province end

//Show home cities
function SelectHomeCityByProvinceId(pId)
{
    try
    {
        WSLogin.SelectCityByProvinceId(pId,OnCompleteGetHomeCity, OnTimeOut, OnError);
     }
     catch(ex)
     {
        alert(ex.message);
     }
}

function OnCompleteGetHomeCity(args)
{
    var listCity = document.getElementById("listHomeCity");
    
    listCity.options.length=0;
    for(var i=0;i<args.ObjList.length;i++)
    {
        var option = new Option(args.ObjList[i].Name,args.ObjList[i].ID);
        listCity.add(option);
    }
}
// show home province end

// Show trip hobby
function SelectTripHobby()
{
    try
    {
        WSLogin.SelectTripHobby(OnCompleteSelectTripHobby, OnTimeOut, OnError);
     }
     catch(ex)
     {
        alert(ex.message);
     }
}

function OnCompleteSelectTripHobby(args)
{
    var tripHobby = document.getElementById("tripHobby");

    for(var i=0;i<args.ObjList.length;i++)
    {
        tripHobby.innerHTML += String.format("<input id='{0}'class='inputNone' value='{1}' type='checkbox'/>{2}",
            "tripHobby" + args.ObjList[i].ID,args.ObjList[i].ID,args.ObjList[i].Text);
    }
}

// end show trip hobby

// Show trip hobby
function SelectTripType()
{
    try
    {
        WSLogin.SelectTripType(OnCompleteSelectTripType, OnTimeOut, OnError);
     }
     catch(ex)
     {
        alert(ex.message);
     }
}

function OnCompleteSelectTripType(args)
{
    var tripType = document.getElementById("tripType");

    for(var i=0;i<args.ObjList.length;i++)
    {
        tripType.innerHTML += String.format("<input id='{0}'class='inputNone' value='{1}' type='checkbox'/>{2}",
            "tripType" + args.ObjList[i].ID,args.ObjList[i].ID,args.ObjList[i].Text);
    }
}

// end show trip hobby

// Update user profile for reg
function UpdateUserProfile(isRedirect)
{
    try
    {
        var gender = document.getElementById('male').checked?'M':'F';
        var birthYear = document.getElementById('birthYear').value;
        var birthMonth = document.getElementById('birthMonth').value;
        var birthDay = document.getElementById('birthDay').value;
        var listHomeProvince = document.getElementById('listHomeProvince').value;
        var listHomeCity = document.getElementById('listHomeCity').value;
        var listProvince = document.getElementById('listProvince').value;
        var listCity = document.getElementById('listCity').value;
        var mobilePhone = document.getElementById('mobilePhone').value;
        var qq = document.getElementById('qq').value;
        var msn = document.getElementById('msn').value;
        
        var userProfile = {"Gender":gender,"BirthYear":birthYear,"BirthMonth":birthMonth,"BirthDay":birthDay,
                           "HomeProvinceId":listHomeProvince,"HomeCityId":listHomeCity,"ProvinceID":listProvince,
                           "CityID":listCity,"MobilePhone":mobilePhone,"QQ":qq,"MSN":msn};
        
        WSLogin.UpdateUserProfile(userProfile,OnCompleteUpdateUserProfile, OnTimeOut, OnError);
     }
     catch(ex)
     {
        alert(ex.message);
     }
     
    function OnCompleteUpdateUserProfile(args)
    {
        if(!args)
        {
            alert("failed");
        }
        else
        {
            if(isRedirect)
            {
                window.location.href='register_step3.aspx';
            }
            else
            {
                alert("更改成功");
            }
        }
    }
}


// end

//Show home cities
function SelectByCityId(pageSize, pageIndex)
{
    try
    {
        currentPageIndex = pageIndex;
        WSLogin.SelectByCityId(pageSize, pageIndex,OnCompleteSelectByCityId, OnTimeOut, OnError);
        
        if(pageIndex>1)
        {
            currentIndexIndex = parseInt((pageIndex-1)/indexSize)+1;
        }
     }
     catch(ex)
     {
        alert(ex.message);
     }
     
    function OnCompleteSelectByCityId(args)
    {
        if(args && args.ObjList)
        {
            var markers = document.getElementById("markers");
             markers.innerHTML = "";
            for(var i=0;i<args.ObjList.length;i++)
            {
                markers.innerHTML += 
                    String.format('<li><img src="images/ico_mark.jpg" /><a href="#" onclick="showAddress(this.innerHTML);return false;">{0}</a></li>',args.ObjList[i].Name);
            }
            
            var pageIndex = document.getElementById("pageIndex");
            pageIndex.innerHTML = "";
            
    //        var selectedIndex = currentPageIndex%indexSize;
    //        if(selectedIndex==0)
    //        {
    //            selectedIndex = indexSize;
    //        }

            if(currentIndexIndex>1)
            {
                pageIndex.innerHTML += previousPageTemplate;
            }

            for(i = indexSize*currentIndexIndex-indexSize+1;i<=indexSize*currentIndexIndex;i++)
            {
                if(currentPageIndex==i)
                {
                    pageIndex.innerHTML += String.format(selectedTemplate,i);
                }
                else
                {
                    pageIndex.innerHTML += String.format(notSelectedTemplate,i,i);
                }
            }
            
            maxIndexIndex = parseInt(args.IndexCount/(indexSize*pageSize)) + 1;
            if(currentIndexIndex<maxIndexIndex)
            {
                
                pageIndex.innerHTML += nextPageTemplate;
            }
        }
    }
}

function fillPageIndex(pageIndexDiv)
{
    
}

var previousPageTemplate = '<a id="nextPage" href="#" onclick="SelectByCityId(pageSize,currentPageIndex-1);return false">上一页</a>';
var nextPageTemplate =     '<a id="nextPage" href="#" onclick="SelectByCityId(pageSize,currentPageIndex+1);return false">下一页</a>';

var selectedTemplate = '<font class="nowpage">{0}</font>';
var notSelectedTemplate = '<a href="#" onclick="SelectByCityId(pageSize,{0});return false">{1}</a>';
// show home province end

// SelectAllCityView
function SelectAllCityView()
{
    try
    {
        WSLogin.SelectAllCityView(OnCompleteSelectAllCityView, OnTimeOut, OnError);
     }
     catch(ex)
     {
        alert(ex.message);
     }
}

function OnCompleteSelectAllCityView(args)
{
//    var intIndex=0;arrList1 = new Array();
//    arrList1[intIndex++] = " www.sina.com.com";
//    arrList1[intIndex++] = "业务员";
//    arrList1[intIndex++] = "业务精英";
//    arrList1[intIndex++] = "业务主管";
//    arrList1[intIndex++] = "4444dsafasdf";
//    arrList1[intIndex++] = "dddsfddsafdsaf";
//    arrList1[intIndex++] = "121213dsafsdaf";
//    arrList1[intIndex++] = "43213asdfadsf";
//    arrList1[intIndex++] = "dsa3121dasf3";
//    arrList1[intIndex++] = "上海浦东";
    arrList1 = args.ObjList;
    smanPromptList("arrList1","ToCity");
}

// end show all city view

// Validate
function checkRegular(message)
{
	var reg = new RegExp("^[_A-Za-z0-9\u4e00-\u9fa5]*$");
	return reg.test(message);
}
function checkEmail(email)
{
    var reg = new RegExp("\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
    if(!reg.test(email))
    {
        showErrorMessage("error_panel","错误! 你输入的Email地址不正确，请检查。");
    }
    else
    {
        removeErrorMessage("error_panel");
    }
}

function showErrorMessage(id,errMsg)
{
    var error_panel = document.getElementById(id);
    error_panel.innerHTML = "";
    error_panel.innerHTML = errMsg;
}
function removeErrorMessage(id)
{
    var error_panel = document.getElementById(id);
    error_panel.innerHTML = "";
}

var EMAIL_REGULAR_EXPRESSION="(\\w|[-.])+@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
var PASSWORD_REGULAR_EXPRESSION="^\\w{6,20}$";
var NICKNAME_REGULAR_EXPRESSION="^[a-zA-Z0-9\\u4e00-\\u9fa5]{2,20}$";
var TOCITY_REGULAR_EXPRESSION="^[,a-zA-Z0-9\\u4e00-\\u9fa5]{1,200}$";
var EVE_TITLE_REGULAR_EXPRESSION="^[a-zA-Z0-9\\u4e00-\\u9fa5]{1,250}$";
var EVE_MEMO_REGULAR_EXPRESSION="^[,.?，。？a-zA-Z0-9\\u4e00-\\u9fa5]{1,1000}$";

function requireFieldValid(controlToValidID,msgSpanID,errorMessage)
{
    var objControlToValid=document.getElementById(controlToValidID);
    var objSpan=document.getElementById(msgSpanID);
    var isValid=objControlToValid.value.trim()!='';
    if(!isValid)
    {
        objSpan.style.display = "block";
        objSpan.innerHTML = "";
        objSpan.innerHTML = errorMessage;
    }
    else
    {
        objSpan.style.display = "none";
    }
    return isValid;
}

function regularExpressionValid(controlToValidID,validationExpression,msgSpanID, errorMessage)
{
    var objRegExp = new RegExp(validationExpression,"g");
    var objControlToValid=document.getElementById(controlToValidID);
    var objSpan=document.getElementById(msgSpanID);
    var isValid=objRegExp.test(objControlToValid.value);
    if(!isValid)
    {
        objSpan.style.display = "block";
        objSpan.innerHTML = "";
        objSpan.innerHTML = errorMessage;
    }
    else
    {
        objSpan.style.display = "none";
    }
    return isValid;
}

//Auto complete//////////////////////////////////
function suckerfish(type, tag, parentId)
{
        if (window.attachEvent)
        {
                window.attachEvent("onload", function()
                {
                        var sfEls = (parentId==null)?

document.getElementsByTagName(tag):document.getElementById(parentId).getElementsByTagName(tag);
                        type(sfEls);
                });
        }
}
sfFocus = function(sfEls)
{
        for (var i=0; i<sfEls.length; i++)
        {
            // for text only
            if(sfEls[i].type == "text" && sfEls[i].tagName == "INPUT" || sfEls[i].tagName != "INPUT")
            {
                sfEls[i].onfocus=function()
                {
                        this.className+=" sffocus";
                        if( this.value == this.defaultValue ) { this.value = ""; }
                }
                sfEls[i].onblur=function()
                {
                        this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
                        if( this.value == "" ) { this.value = this.defaultValue; }
                                        }
             }
        }
}

//suckerfish(sfFocus, "INPUT");
//suckerfish(sfFocus, "TEXTAREA"); 
//suckerfish(sfFocus, "SELECT"); 

function smanPromptList(strList,objInputId)
{

    arrList = new Array();
    this.style = "background:#E8F7EB;border: 1px solid #CCCCCC;font-size:14px;cursor: default;"

    function load() 
    {
	    var tmpStr1 = strList.split(",");
	    for(i=0;i<tmpStr1.length;i++)
	    {
		    arrList[i] = eval(tmpStr1[i])
//		    arrList[i].sort(
//		    function(a,b)
//		    {
//		        if(a.length>b.length)return 1;
//		        else if(a.length==b.length)return a.localeCompare(b);
//		        else return -1;
//		    })
	    }   
        var selectedIndex=-1;
        var intTmp; //循环用的:)
        var objouter=document.getElementById("__smanDisp") //显示的DIV对象
        var objInput = document.getElementById(objInputId); //文本框对象
//        var objInput2 = document.getElementById("inputer2"); //文本框对象
        var tmpStr = objInputId.split(",");
        for(i=0;i<tmpStr.length;i++)
        {
	        var objInput = document.getElementById(tmpStr[i]); //文本框对象
            //if (objInput==null) {alert('smanPromptList初始化失败:没有找到"'+objInputId+'"文本框');return ;}
            //文本框失去焦点
            objInput.onblur=function()
            {
                objouter.style.display='none';
            }
            window.onfocus=function()
            {
                objouter.style.display='none';
            }
            //文本框按键抬起
            objInput.onkeyup=checkKeyCode;
            //文本框得到焦点
            objInput.onfocus=checkAndShow;
        }
        
        function checkKeyCode(obj)
        {
            var ie = (document.all)? true:false
            if (ie)
            {
                var keyCode=event.keyCode
                if (keyCode==40||keyCode==38)
                { //下上
                  var isUp=false
                  if(keyCode==40) 
                    isUp=true ;
                  chageSelection(isUp)
                }
                else if (keyCode==13)
                {//回车
                    outSelection(selectedIndex);
                }
                else
                {
                    checkAndShow()
                }
            }
            else
            {
                checkAndShow()
            }
            divPosition()
        }

        function checkAndShow()
        {
            var objInput=null;
            var objList;
            for(i=0;i<document.all.tags('INPUT').length;i++) 
            {
                if(document.activeElement.islist=="true")
                {
	                var objInput=document.activeElement;
	                var objInputId = objInput.id;
	                objList = arrList[objInput.list];
	                //alert(objList.length)
                }
            }
            if(objInput!=null)
            {
                var strInput = objInput.value
                if (strInput!="")
                {
                    divPosition();
                    selectedIndex=-1;
                    objouter.innerHTML ="";
                    for (intTmp=0;intTmp<objList.length;intTmp++)
                    {
                        for(i=0;i<objList[intTmp].CityViewString.length;i++)
                        {
                            if (objList[intTmp].CityViewString.substr(i, strInput.length).toUpperCase()==strInput.toUpperCase())
                            {
                                addOption(objList[intTmp].CityViewString,strInput,objList[intTmp].CityID,objList[intTmp].ID);
                            }
                        }
                    }
                    objouter.style.display='';
                }
                else
                {
                    objouter.style.display='none';
                }
            }
        
            function addOption(value,keyw, cityId, viewId)
            {
                var v=value.replace(keyw,"<b><font color=red>"+keyw+"</font></b>");
                  objouter.innerHTML +="<div onmouseover=\"this.className='sman_selectedStyle'\" onmouseout=\"this.className=''\" onmousedown=\"var objInput = document.getElementById('"+objInputId+"');objInput.value='" + value + "';objInput.setAttribute('CityID'," + cityId + ");objInput.setAttribute('ViewID'," + viewId +");window.focus();\">" + v + "</div>" 
            }
        }
            
        function chageSelection(isUp)
        {
            if (objouter.style.display=='none')
            {
            objouter.style.display='';
            }
            else
            {
                if (isUp)
                  selectedIndex++
                else
                  selectedIndex--
            }
            var maxIndex = objouter.children.length-1;
            if (selectedIndex<0){selectedIndex=0}
            if (selectedIndex>maxIndex) 
            {
                selectedIndex=maxIndex
            }
            for (intTmp=0;intTmp<=maxIndex;intTmp++)
            {
                if (intTmp==selectedIndex)
                {
                    objouter.children[intTmp].className="sman_selectedStyle";
                }
                else
                {
                    objouter.children[intTmp].className="";
                }
            }
        }
        
        function outSelection(Index)
        {
            if(!objouter.children[Index])
                return;
            objInput.value = objouter.children[Index].innerText;
            objouter.style.display='none';
        }
        
        function divPosition()
        {
            var objInput=null;
            for(i=0;i<document.all.tags('INPUT').length;i++) 
            {
	            if(document.activeElement.islist=="true")
	            {
		            var objInput=document.activeElement;
	            }
            }
            if(objInput!=null)
            {
                objouter.style.top =getAbsoluteHeight(objInput)+getAbsoluteTop(objInput);
                objouter.style.left =getAbsoluteLeft(objInput); 
                objouter.style.width=getAbsoluteWidth(objInput)
            }
        }
    }
    
//   window.onload = load;

        
    window.document.body.innerHTML += "<div id='__smanDisp' style='position:absolute;display:none;" + this.style + "' onbulr> </div>";
    window.document.body.innerHTML +="<style>.sman_selectedStyle{background-Color:#102681;color:#FFFFFF}</style>";
    load();
    function getAbsoluteHeight(ob)
    {
        return ob.offsetHeight
    }
    
    function getAbsoluteWidth(ob)
    {
        return ob.offsetWidth
    }
    
    function getAbsoluteLeft(ob)
    {
        var s_el=0;el=ob;while(el){s_el=s_el+el.offsetLeft;el=el.offsetParent;}; return s_el
    }
    
    function getAbsoluteTop(ob)
    {
        var s_el=0;el=ob;while(el){s_el=s_el+el.offsetTop ;el=el.offsetParent;}; return s_el
    }
}   

////////Auto complete end///////////////

var TRIP_PLAN = '<div id="TP{0}" class="TimeTitle"><table border="0" cellspacing="0" cellpadding="0"><tr><td class="LeftBg"></td><td class="CenterBg" valign="middle"><a href="tripplan_2.html">{1}</a></td><td class="RightBg"></td></tr></table>{2}</div>';

var TIME_BOX = '<div id="{0}" class="TimeBox">{1}</div>';
var TRIP_CITY = '<div EleType="CITY" id="{0}" class="TodayTitle"><a href=""><b>{1}</b></a></div>';
var TRIP_VIEW = '<ul cityId="{0}" id="{1}"><li><a href=""><img src="images/ico_a.gif" /> {2}</a></li></ul>';

//Initial trip
function InitialTrip(btnAdd2Id)
{
    ret = false;
    var fromCity;
    try
    {
        var errorPanel = "tabPage1ErrorPanel";
        if(regularExpressionValid('ToCity',TOCITY_REGULAR_EXPRESSION,errorPanel,'目的城市 输入有误!'))
        {
            fromCity = $get('fromCityId').value;
            var ToCity=$get('ToCity');
            
            var eventH = {"StartCityId":fromCity};
            var eventDetail = {"ToCityId":ToCity.getAttribute("CityID")};
            var eventView = {"CityID":ToCity.getAttribute("CityID"),"ViewId":ToCity.getAttribute("ViewId"),"CityView":ToCity.value};
        
            WSLogin.InitialTrip(eventH, eventDetail, eventView, OnCompleteInitialTrip, OnTimeOut, OnError);
        }
        else
        {
            clickBtnSucc = false;
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteInitialTrip(args)
    {
        if(!args.Ret)
        {
            alert("添加失败");
        }
        else
        {
            ret = true;
            clickBtnSucc = true;
            // fill added td
            var toCities = document.getElementById("toCities");
            
            var arr = $get('ToCity').value.split(/,/);
            toCities.innerHTML += String.format("<div id='EV{0}'><img EdId={1} EvId={2} onclick='DeleteEventDetailView(this.EdId, this.EvId,{3},{4})' src='images/butn_closeb.jpg' /> <font class='font16'>{5}</font>准备第 <input onblur='SetDayNumber({6},this.value,{7},{8},{9},{10},\"{11}\",\"{12}\")' type='text' style='width:20px;' /> 天到达此地方</div>",
                                                       args.EdId,args.EdId,args.EvId,$get('ToCity').getAttribute("CityID"),$get('ToCity').getAttribute("ViewId"),                              $get('ToCity').value,                  args.EdId,fromCity,args.EvId,$get('ToCity').getAttribute("CityID"),$get('ToCity').getAttribute("ViewId"),arr[0],arr[1]);
            
            var btnAdd2 = document.getElementById(btnAdd2Id);
            btnAdd2.style.display = "block";
            
            var btnInitialTrip = document.getElementById("btnInitialTrip");
            btnInitialTrip.style.display = "none";
            
            var createTripStep2 = document.getElementById("createTripStep2");
            createTripStep2.style.display = "block";

            var planTime = document.getElementById("planTime");
            
            var fromCityName = document.getElementById("fromCityName").innerHTML;
            
//            var ToCity=document.getElementById('ToCity');
//            var arr = ToCity.value.split(/,/);
//            var tripView = String.format(TRIP_VIEW,ToCity.getAttribute("CityID"),args.EvId + "|" + ToCity.getAttribute("ViewId"),arr[1]);
//            var tripCity = String.format(TRIP_CITY,args.EdId + "|" + ToCity.getAttribute("CityID"),arr[0]);
//            
            // unscheduled
            addTripViewTripCityToUnscheduled(args.EvId,args.EdId);
//            document.getElementById("Unscheduled").innerHTML +=tripCity+tripView;
            
            planTime.innerHTML += 
                String.format(TRIP_PLAN,$get('fromCityId').value + "|1","行程第1天",
                                        String.format(TIME_BOX,fromCity,String.format(TRIP_CITY,args.FromEdId + "|" + fromCity,fromCityName)));
            
            $get('fromCityId').setAttribute("ehId",args.EhId);
            $get('txtEhId').value = args.EhId;
//            window.location.href = args.Url;
        }
    }
    
    return ret;
}
//Initial trip end

//add trip detail
function InsertEventDetailView()
{
    ret = false;
    try
    {
        var errorPanel = "tabPage1ErrorPanel";
        if(regularExpressionValid('ToCity',TOCITY_REGULAR_EXPRESSION,errorPanel,'目的城市 输入有误!'))
        {
//            var unscheduledPannel = document.getElementById("Unscheduled");
//            unscheduledPannel
            var ToCity=$get('ToCity');
            var ehId = $get('fromCityId').getAttribute("ehId");
            var eventDetail = {"ToCityId":ToCity.getAttribute("CityID"),"EventHId":ehId};
            var eventView = {"CityID":ToCity.getAttribute("CityID"),"ViewId":ToCity.getAttribute("ViewId")};
            
            WSLogin.InsertEventDetailView(eventDetail, eventView, OnCompleteInsertEventDetailView, OnTimeOut, OnError);
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteInsertEventDetailView(args)
    {
        if(!args.Ret)
        {
            alert("添加失败");
        }
        else
        {
            ret = true;
            var toCities = document.getElementById("toCities");
//            toCities.innerHTML += String.format("<div id='EV{0}'><img EdId={1} EvId={2} onclick='DeleteEventDetailView(this.EdId, this.EvId,{3},{4})' src='images/butn_closeb.jpg' /> <font class='font16'>{5}</font>准备第 <input onblur='SetDayNumber({6},this.value,{7},{8})' type='text' style='width:20px;' /> 天到达此地方<div>",
//                                                      args.EdId,     args.EdId,args.EvId,        $get('ToCity').getAttribute("CityID"),$get('ToCity').getAttribute("ViewId"),                                $get('ToCity').value,                             args.EdId);

            var arr = $get('ToCity').value.split(/,/);
            toCities.innerHTML += String.format("<div id='EV{0}'><img EdId={1} EvId={2} onclick='DeleteEventDetailView(this.EdId, this.EvId,{3},{4})' src='images/butn_closeb.jpg' /> <font class='font16'>{5}</font>准备第 <input onblur='SetDayNumber({6},this.value,{7},{8},{9},{10},\"{11}\",\"{12}\")' type='text' style='width:20px;' /> 天到达此地方</div>",
                                                       args.EdId,args.EdId,args.EvId,$get('ToCity').getAttribute("CityID"),$get('ToCity').getAttribute("ViewId"),                              $get('ToCity').value,                  args.EdId,$get('fromCityId').value,args.EvId,$get('ToCity').getAttribute("CityID"),$get('ToCity').getAttribute("ViewId"),arr[0],arr[1]);
            


//            var ToCity=document.getElementById('ToCity');
//            var arr = ToCity.value.split(/,/);

//            var tripView = String.format(TRIP_VIEW,args.EvId + "|" + ToCity.getAttribute("ViewId"),arr[1]);
//            var tripCity = String.format(TRIP_CITY,args.EdId + "|" + ToCity.getAttribute("CityID"),arr[0]);
//            
//            // unscheduled
//            document.getElementById("Unscheduled").innerHTML +=tripCity+tripView;
             addTripViewTripCityToUnscheduled(args.EvId,args.EdId);
        }
    }
    
    return ret;
}
//add trip detail end

//add trip_view and trip_city to unscheduled pannel
function addTripViewTripCityToUnscheduled(evId,edId)
{
    var ToCity=document.getElementById('ToCity');
    
    var tcId = edId + "|" + ToCity.getAttribute("CityID");
    var tvId = evId + "|" + ToCity.getAttribute("ViewId");
    
    var arr = ToCity.value.split(/,/);
    var tripView = String.format(TRIP_VIEW,ToCity.getAttribute("CityID"),tvId,arr[1]);
    var tripCity = String.format(TRIP_CITY,tcId,arr[0]);
//    var divArr = $get("Unscheduled").getElementsByTagName("div");

    var timeBox = GetUnscheduledTimebox(ToCity.getAttribute("CityID"));
    
    var hasCity = false;
    
    if(timeBox)
    {
        var divArr = timeBox.getElementsByTagName("div");
        for(var i=0;i<divArr.length;i++)
        {
            if(divArr[i].id.split(/\|/)[1]==ToCity.getAttribute("CityID"))
            {
                hasCity = true;
                break;
            }
        }

        if(hasCity)
        {
            timeBox.innerHTML += tripView;
        }
        else
        {
            timeBox.innerHTML +=tripCity+tripView;
        }
    }
    else
    {
        $get("Unscheduled").innerHTML += String.format(TIME_BOX,ToCity.getAttribute("CityID"),tripCity+tripView);
    }
}
//add trip_view and trip_city to unscheduled pannel end

var prefix = "TP";
//add trip_view and trip_city to unscheduled pannel
function addTripViewTripCityToTimeTitle(timeTitleId,evId,edId,toCityId, toViewId,toCityName, toViewName)
{
//    var ToCity=document.getElementById('ToCity');
    
    var tcId = edId + "|" + toCityId;
    var tvId = evId + "|" + toViewId;
    
//    var arr = ToCity.value.split(/,/);
    var tripView = String.format(TRIP_VIEW,toCityId,tvId,toViewName);
    var tripCity = String.format(TRIP_CITY,tcId,toCityName);
//    var divArr = $get("Unscheduled").getElementsByTagName("div");

    var timeBox = GetScheduledTimebox(prefix + timeTitleId,toCityId);
    
    var hasCity = false;
    
    if(timeBox)
    {
        var divArr = timeBox.getElementsByTagName("div");
        for(var i=0;i<divArr.length;i++)
        {
            if(divArr[i].id.split(/\|/)[1]==toCityId)
            {
                hasCity = true;
                break;
            }
        }

        if(hasCity)
        {
            timeBox.innerHTML += tripView;
            
        }
        else
        {
            timeBox.innerHTML +=tripCity+tripView;
        }
    }
    else
    {
        $get(prefix + timeTitleId).innerHTML += String.format(TIME_BOX,toCityId,tripCity+tripView);
    }
}
//add trip_view and trip_city to unscheduled pannel end

//Get unscheduled time box 
function GetUnscheduledTimebox(cityId)
{
    var timeBox;
    for(var i=0;i<$get("Unscheduled").childNodes.length;i++)
    {
        if($get("Unscheduled").childNodes[i].nodeName == "DIV" && $get("Unscheduled").childNodes[i].id==cityId)
        {
            timeBox = $get("Unscheduled").childNodes[i];
            break;
        }
    }
    
    return timeBox;
}

//Get unscheduled time box end

//Get scheduled time box 
function GetScheduledTimebox(timeTitleId,cityId)
{
    var timeBox;
    for(var i=0;i<$get(timeTitleId).childNodes.length;i++)
    {
        if($get(timeTitleId).childNodes[i].nodeName == "DIV" && $get(timeTitleId).childNodes[i].id==cityId)
        {
            timeBox = $get(timeTitleId).childNodes[i];
            break;
        }
    }
    
    return timeBox;
}

//Get scheduled time box end

// check time title

function CheckTimeTitle(ttId)
{
    var planTime = $get("planTime");
    var hasttId = false;
    for(var i=0;i<planTime.childNodes.length;i++)
    {
        if(planTime.childNodes[i].nodeName == "DIV" && planTime.childNodes[i].id=="TP" + ttId)
        {
            hasttId = true;
            break;
        }
    }
    
    if(!hasttId)
    {
        planTime.innerHTML += String.format(TRIP_PLAN,ttId,ttId.split(/\|/)[1],"");
    }
}

// check time title end

//delete trip_view trip_city from unscheduled
function delTripViewTripCityFromUnscheduled(evId,edId,cityId,viewId)
{
//    var ToCity=document.getElementById('ToCity');
//    var arr = ToCity.value.split(/,/);
//    
    var tvId = evId + "|" + viewId;
    var tcId = edId + "|" + cityId;

//    var tripView = String.format(TRIP_VIEW,tvId,arr[1]);
//    var tripCity = String.format(TRIP_CITY,tcId,arr[0]);
    
    var viewCount = 0;
    
    var timeBox = GetUnscheduledTimebox(cityId);
    
    if(timeBox)
    {
        var viewArr = timeBox.getElementsByTagName("ul");
        for(var i=0;i<viewArr.length;i++)
        {
            if(viewArr[i].cityId == cityId)
            {
                viewCount ++;
            }
        }

        if(viewCount>1)
        {
            if($get(tvId)) timeBox.removeChild($get(tvId));
        }
        else
        {
            // unscheduled
           if($get(tvId)) timeBox.removeChild($get(tvId));
            if($get(tcId)) timeBox.removeChild($get(tcId));
        }
    }
    // unscheduled
//    $get("Unscheduled").removeChild($get(tvId));
//    $get("Unscheduled").removeChild($get(tcId));
}
//delete trip_view trip_city from unscheduled end

//delete trip_view trip_city from scheduled
function delTripViewTripCityFromScheduled(timeTitleId,evId,edId,cityId,viewId)
{
//    var ToCity=document.getElementById('ToCity');
//    var arr = ToCity.value.split(/,/);
//    
    var tvId = evId + "|" + viewId;
    var tcId = edId + "|" + cityId;

//    var tripView = String.format(TRIP_VIEW,tvId,arr[1]);
//    var tripCity = String.format(TRIP_CITY,tcId,arr[0]);
    
    var viewCount = 0;
    
    var timeBox = GetScheduledTimebox(prefix + timeTitleId,cityId);
    
    if(timeBox)
    {
        var viewArr = timeBox.getElementsByTagName("ul");
        for(var i=0;i<viewArr.length;i++)
        {
            if(viewArr[i].cityId == cityId)
            {
                viewCount ++;
            }
        }

        if(viewCount>1)
        {
            if($get(tvId)) timeBox.removeChild($get(tvId));
        }
        else
        {
            // unscheduled
           if($get(tvId)) timeBox.removeChild($get(tvId));
            if($get(tcId)) timeBox.removeChild($get(tcId));
        }
    }
    // unscheduled
//    $get("Unscheduled").removeChild($get(tvId));
//    $get("Unscheduled").removeChild($get(tcId));
}
//delete trip_view trip_city from scheduled end

//Update day number
function SetDayNumber(EdId,dayNum,fromCity,EvId, toCityId, toViewId, toCityName, toViewName)
{
    if(!dayNum)
        return true;
        
    ret = false;
    try
    {
        WSLogin.SetDayNumber(EdId, dayNum, OnCompleteSetDayNumber, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSetDayNumber(args)
    {
        if(!args)
        {
            alert("添加失败");
        }
        else
        {
            var ttId = fromCity + "|" + dayNum;
            $get("EV" + EdId).setAttribute("ttId",ttId);
            CheckTimeTitle(ttId);
            addTripViewTripCityToTimeTitle(ttId,EvId,EdId,toCityId,toViewId,toCityName,toViewName);
            delTripViewTripCityFromUnscheduled(EvId,EdId,toCityId, toViewId);
        }
    }
    
    return ret;
}
//add trip detail end

//delete event detail view
function DeleteEventDetailView(EdId,EvId,cityId,viewId)
{
    ret = false;
    try
    {
        WSLogin.DeleteEventDetailView(EdId, EvId, OnCompleteDeleteEventDetailView, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteDeleteEventDetailView(args)
    {
        if(!args.Ret)
        {
            alert("添加失败");
        }
        else
        {
            ret = true;
            var toCities = document.getElementById("toCities");
            var ttId = $get("EV" + EdId).getAttribute("ttId");
            toCities.removeChild($get("EV" + EdId));

            if(ttId)
            {
                delTripViewTripCityFromScheduled(ttId,EvId,EdId,cityId,viewId);
            }
            else
            {
                // Remove unscheduled element
                delTripViewTripCityFromUnscheduled(EvId,EdId,cityId,viewId);
            }
        }
    }
    
    return ret;
}
//add trip detail end

//CreateTrip2
function CreateTrip2()
{
    ret = false;
    try
    {
        var errorPanel = "error_panel";
        if(true)//regularExpressionValid('ToCity',TOCITY_REGULAR_EXPRESSION,errorPanel,'目的城市 输入有误!'))
        {
            var StartDate = document.getElementById('startDate').value;
            var DueDays=document.getElementById('dueDays').value;
            
            var ehId = document.getElementById('txtEhId').value;
            
            var eventH = {"StartDateStr":StartDate.replace(/-/g,'/'),"DueDays":DueDays,"Id":ehId};

            WSLogin.CreateTrip2(eventH, OnCompleteCreateTrip2, OnTimeOut, OnError);
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteCreateTrip2(args)
    {
        if(!args)
        {
            alert("添加失败");
        }
        else
        {
            ret = true;
        }
    }
    
    return ret;
}
//CreateTrip2 end

//Get Trip plan detail
var requestParam = null;
function GetTripPlanDetail()
{
    ret = false;
    try
    {
        if(requestParam)
        {
            WSLogin.GetTripPlanDetail(requestParam.ehId, OnCompleteGetTripPlanDetail, OnTimeOut, OnError);
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteGetTripPlanDetail(args)
    {
        if(!args.Ret)
        {
            alert("添加失败");
        }
        else
        {
            var selectCities = $get("selectCities");
            for(var i=0;i<args.Eds.length;i++)
            {
                var option = new Option(args.Eds[i].ToCityName,args.Eds[i].ToCityId);
                selectCities.add(option);
            }
            SelectCitiesChangeHandle(selectCities.value);
        }
    }
    
    return ret;
}

//Get trip plan detail end

//Get event view start
function SelectCitiesChangeHandle(cityId)
{
    ret = false;
    try
    {
        if(cityId)
        {
            WSLogin.SelectEventViewByCityId(cityId, OnCompleteGetTripPlanDetail, OnTimeOut, OnError);
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteGetTripPlanDetail(args)
    {
        var Evs = $get("Evs");
        var selectedViews = $get("selectedViews");
        if(!args.Ret)
        {
            Evs.innerHTML = "";
        }
        else
        {
            Evs.innerHTML = args.VsInnerHTML;
            selectedViews.innerHTML = args.EvsInnerHTML;
        }
    }
    
    return ret;
}

//Get event view end

//Insert event view start
function InsertEventView(viewId)
{
    ret = false;
    try
    {
        var eventView = {"CityID":$get("selectCities").value,"ViewId":viewId};
        
        WSLogin.InsertEventView(eventView, OnCompleteInsertEventView, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteInsertEventView(args)
    {
        if(!args.Ret)
        {
            if(!args.IsLogin)
            {
                alert("请登陆后再添加!");
            }
            else
            {
                alert("添加失败");
            }
        }
        else
        {
            var selectedViews = $get("selectedViews");
            selectedViews.innerHTML += args.EvsInnerHTML;
        }
    }
    
    return ret;
}
//Insert event view end

//Insert event view start
function DeleteEventView(evId)
{
    ret = false;
    try
    {
        var eventView = {"Id":evId.split("|")[1]};
        
        WSLogin.DeleteEventView(eventView, OnCompleteInsertEventView, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteInsertEventView(args)
    {
        if(!args.Ret)
        {
            alert("删除失败");
        }
        else
        {
            $get("selectedViews").removeChild($get(evId).parentNode);
        }
    }
    
    return ret;
}
//Insert event view end

//Insert event view start
function GetTrips(ehId)
{
    ret = false;
    try
    {
        WSLogin.GetTrips(ehId, OnCompleteGetTrips, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteGetTrips(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            $get("planTime").innerHTML =args.Trips;
        }
    }
    
    return ret;
}
//Insert event view end

// select all trip comments
var commentTemplate = "<div id='{0}' class='commentCont'><div class='headPic'><a href='tfuserprofile.aspx?uid={7}'><img src='{1}' width='50px' /></a></div><div class='commentItem'><div class='title'><span>{2}</span>{3}<a href='tfuserprofile.aspx?uid={4}'>{5}</a></div>{6}</div><div class='clear'></div></div>";

var LOADING_INTERVAL = 500;
var LOADING_COLOR = '#00b277';
var loadingTimer;
var loadingLoopCounter = 1;
var maxLoadingLoop = 10;
function beginProgress(divProgress)
{
    divProgress.style.display = '';
    clearProgress();
    loadingTimer = setTimeout(updateProgress, LOADING_INTERVAL);
}

function updateProgress()
{
    loadingLoopCounter += 1;

    if (loadingLoopCounter <= maxLoadingLoop)
    {
        document.getElementById('loadingProgress' + loadingLoopCounter).style.backgroundColor = LOADING_COLOR;
    }
    else 
    {
        clearProgress();
    }

    if (loadingTimer)
    {
        clearTimeout(loadingTimer);
    }

    loadingTimer = setTimeout(updateProgress, LOADING_INTERVAL);
}

function clearProgress()
{
    for (var i = 1; i <= maxLoadingLoop; i++)
    {
        document.getElementById('loadingProgress' + i).style.backgroundColor = 'transparent';
    }

    document.getElementById('loadingProgress1').style.backgroundColor = LOADING_COLOR;
    loadingLoopCounter = 1;
}

function loadingComplete(divProgress)
{
    clearProgress();
    if (loadingTimer)
    {
        clearTimeout(loadingTimer);
    }

    divProgress.style.display = 'none';
}

function SelectEHLeaveWord(pageIndex)
{
    ret = false;
    var requestParam = GetRequestParam();
    try
    {
        if(requestParam)
        {
            WSLogin.SelectLeaveWordByEleId(requestParam.ehId,"eh",10,pageIndex, OnCompleteSelectEHLeaveWord, OnTimeOut, OnError);
            beginProgress($get('divProgress'));
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectEHLeaveWord(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            var delComment = '';
            
            $get("EHComment").innerHTML = '';
            for(var i=0;i<args.LeaveWords.length;i++)
            {
                var lv = args.LeaveWords[i];
                // if user login ,it can delete the comment
                if(args.IsLogin)
                {
                    delComment = String.format("<a href='#' onclick='delLeaveword({0},\"{1}\");return false;'>删除</a>",lv.Id,'eh');
                }
                $get("EHComment").innerHTML += String.format(commentTemplate,lv.Id,lv.Pic,delComment,lv.Keyin_date,lv.Uid,lv.Nick_Name,lv.LeaveWords,lv.Uid);
            }
            
            showDataGridFooter(args.MaxPageIndex,pageIndex,"EHCommentFooter",10, "SelectEHLeaveWord");
            
            loadingComplete($get('divProgress'));
            $get("leaveWordCount").innerHTML = args.ObjectCount;
            
        }
    }
    
    return ret;
}
// select all trip comments end

// delete word
function delLeaveword(lvId, commentType)
{
    ret = false;
    var leaveWord;
    try
    {
        WSLogin.DeleteLeaveWords(lvId, OnCompleteDeleteLeaveWords, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteDeleteLeaveWords(args)
    {
        if(!args.Ret)
        {
            alert("删除失败");
        }
        else
        {
            switch(commentType)
            {
                case "eh":
                    SelectEHLeaveWord(1);
                    break;
                case "pic":
                    SelectPicLeaveWord(1);
                    break;
                case "blg":
                    UpdateBlogCommentCount(-1);
                    
                default:
                    break;
            }
            
        }
    }
    
    return ret;
}

// end delete word

// insert comments
function InsertLeaveWordsForEH(ehId)
{
    ret = false;
    var leaveWord;
    try
    {
        leaveWord = {"LeaveWords":$get("LeaveWords").value,"ElementId":ehId,"ElementType":"eh"};
        WSLogin.InsertLeaveWords(leaveWord, OnCompleteInsertLeaveWords, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteInsertLeaveWords(args)
    {
        if(!args.Ret)
        {
            if(!args.IsLogin)
            {
                alert("请登陆后留言");
            }
            else
            {
                alert("失败");
            }
        }
        else
        {
            var searchEHLeaveWordDataGrid = new DataGrid(SelectEHLeaveWord);
            searchEHLeaveWordDataGrid.BindData(1);
//            var lv = args.LeaveWords[0];
//            $get("EHComment").innerHTML += String.format(commentTemplate,lv.Id,lv.Pic,"<a href=''>删除</a>",lv.Keyin_date,lv.Uid,lv.Nick_Name,lv.LeaveWords);
        }
    }
    
    return ret;
}

// insert comments end

// get all event
function SelectAllEH(uid, targetDiv)
{
    ret = false;
    try
    {
        WSLogin.SelectAllEH(10,1,uid, OnCompleteSelectAllEH, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectAllEH(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            $get(targetDiv).innerHTML = args.EhsInnerHTML;
        }
    }
    
    return ret;
}

// get all event end

// get view count string

function removeNextSibling(obj)
{
    // Skip <li>></li>
    var nextSiblingObj = obj.parentNode.nextSibling;
     while(nextSiblingObj.nextSibling != null)
     {
        nextSiblingObj.parentNode.removeChild(nextSiblingObj.nextSibling);
     }
}

var tripListPageSize = 5;
var tripListPageIndex = 1;
function SelectCountryViewCountByCountryId(countryId)
{
    ret = false;
    try
    {
        WSLogin.SelectCountryViewCountByCountryId(countryId,OnCompleteSelectCountryViewCountByCountryId, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectCountryViewCountByCountryId(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            for(var i=0;i<args.ViewCountList.length;i++)
            {
                var tmpId = (i==0?"cId"+countryId:"");
                var viewCountObj = args.ViewCountList[i];
                $get("PlaceTrace").innerHTML += 
                    String.format("<li><a {4} href='#' onclick='removeNextSibling(this);SelectProvinceViewCountByCountryId({0},this);return false'>{1}</a>({2}) </li><li>{3}</li>",
                                   viewCountObj.Id,viewCountObj.Name, viewCountObj.ViewCount,'\>',tmpId);
            }
            // set default provinces
            SelectProvinceViewCountByCountryId(countryId,$get("cId"+countryId));
            // fill Contboxes
            FillContboxes(args);
        }
    }
    
    return ret;
}

function SelectProvinceViewCountByCountryId(countryId, obj)
{
    ret = false;
    try
    {
        WSLogin.SelectProvinceViewCountByCountryId(countryId,tripListPageSize,tripListPageIndex,OnCompleteSelectProvinceViewCountByCountryId, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectProvinceViewCountByCountryId(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
                    
//            $get("PlaceTrace").innerHTML +=  "<li> \> </li>";
            $get("SubPlace").innerHTML = '';
            for(var i=0;i<args.ViewCountList.length;i++)
            {
                var viewCountObj = args.ViewCountList[i];
                $get("SubPlace").innerHTML += 
                    String.format("<li><a href='#' onclick='removeNextSibling(this);SelectCityViewCountByProvinceId({0},this);return false' >{1}({2})</a> </li><li>{3}</li>",
                                   viewCountObj.Id,viewCountObj.Name, viewCountObj.ViewCount,'|');
            }
            
            // fill Contboxes
            FillContboxes(args);            
        }
    }
    
    return ret;
}

function SelectCityViewCountByProvinceId(provinceId, obj)
{
    ret = false;
    try
    {
        WSLogin.SelectCityViewCountByProvinceId(provinceId,tripListPageSize,tripListPageIndex,OnCompleteSelectCityViewCountByProvinceId, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectCityViewCountByProvinceId(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {

            // add the selected province to place trace container
            var isContain = false;
            for(var i=0;i< $get("PlaceTrace").childNodes.length;i++)
            {
                if (obj.parentNode.outerHTML.indexOf($get("PlaceTrace").childNodes[i].innerHTML)>=0)
                {
                    isContain = true;
                    break;
                }
            }
            
            if(!isContain)
            {
                $get("PlaceTrace").innerHTML += obj.parentNode.outerHTML + "<li> \> </li>";
            }
            
            //fill cities to sub place
            $get("SubPlace").innerHTML = '';
            for(var i=0;i<args.ViewCountList.length;i++)
            {
                var viewCountObj = args.ViewCountList[i];
                $get("SubPlace").innerHTML += 
                    String.format("<li><a href='#' onclick='removeNextSibling(this);SelectViewsByCityIdForTripList({0},this);return false' >{1}({2})</a></li><li> | </li>",
                                   viewCountObj.Id,viewCountObj.Name, viewCountObj.ViewCount);
            }

            // fill Contboxes
            FillContboxes(args);
        }
    }
    
    return ret;
}


function SelectViewsByCityIdForTripList(cityId, obj)
{
    ret = false;
    try
    {
        WSLogin.SelectViewsByCityIdForTripList(cityId,tripListPageSize,tripListPageIndex,OnCompleteSelectViewsByCityIdForTripList, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectViewsByCityIdForTripList(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            // add the selected province to place trace container
            var isContain = false;
            for(var i=0;i< $get("PlaceTrace").childNodes.length;i++)
            {
                if (obj.parentNode.outerHTML.indexOf($get("PlaceTrace").childNodes[i].innerHTML)>=0)
                {
                    isContain = true;
                    break;
                }
            }
            
            if(!isContain)
            {
                $get("PlaceTrace").innerHTML += obj.parentNode.outerHTML + "<li> \> </li>";
            }
            
            //fill cities to sub place
            $get("SubPlace").innerHTML = '';
            for(var i=0;i<args.Evs.length;i++)
            {
                var eventView = args.Evs[i];
                $get("SubPlace").innerHTML += 
                    String.format("<li><a href='#' onclick='DisplayView({0});return false' >{1}</a> | </li>",
                                   eventView.Id,eventView.ViewName);
            }
            
            
//            $get("Contboxes").innerHTML = "";
//            for(var i=0;i<args.Ehs.length;i++)
//            {
//                var eh = args.Ehs[i];
//                $get("Contboxes").innerHTML += String.format(contBox,eh.Id,eh.PicUrl, eh.Id, eh.EventTitle, eh.Memo!=null?eh.Memo.substring(0,20)+"...":"","<a href=''>稻城</a> <a href=''>德格</a> <a href=''>贡嘎山</a> <a href=''>甘孜</a> <a href=''>康定</a>",
//                eh.OwnerId,"userName","出发地URL","cityName",eh.TotalCost,"2008.09.06 - 2008.09.12(共7天)","18/50","2008.09.04");
//            }
            
            // fill city info
            if(args.CityInfo)
            {
                $get("cityInfo").innerHTML = 
                    String.format("<h1>{0}</h1>{1}",args.CityInfo.CityName,args.CityInfo.Description);
            }
            
            // fill Contboxes
            FillContboxes(args);
        }
    }
    
    return ret;
}

function FillContboxes(args)
{
    if(args.Ehs && args.Ehs.length>0)
    {
        // fill Contboxes
        $get("Contboxes").innerHTML = "";
        for(var i=0;i<args.Ehs.length;i++)
        {
            var eh = args.Ehs[i];
            $get("Contboxes").innerHTML += String.format(contBox,eh.Id,eh.PicUrl, eh.Id, eh.EventTitle, eh.Memo!=null?eh.Memo.substring(0,20)+"...":"","<a href=''>稻城</a> <a href=''>德格</a> <a href=''>贡嘎山</a> <a href=''>甘孜</a> <a href=''>康定</a>",
            eh.OwnerId,"userName","出发地URL","cityName",eh.TotalCost,"2008.09.06 - 2008.09.12(共7天)","18/50","2008.09.04");
        }
    }
}

var contBox = "<div class='Contbox'><div class='eventPic'><a href='tripplan.aspx?ehId={0}'><img src='{1}' width='100'/></a></div><div class='eventbody'><div><h2><a href='tripplan.aspx?ehId={2}'>{3}</a></h2>{4}</div><table><tr><td style='width:60px;'><b>目的地：</b></td><td style='width:230px;'>{5}</td><td><b>发起人：</b></td><td><a href='TFUserProfile.aspx?uid={6}'>{7}</a></td></tr><tr><td><b>出发地：</b></td><td><a href='{8}'>{9}上海</a></td><td><b>预计费用：</b></td><td>￥{10}</td></tr><tr><td><b>开始时间：</b></td><td>{11}</td><td><b>报名/关注人数：</b></td><td>{12}</td></tr><tr><td><b>报名截止：</b></td><td>{13}</td><td></td><td></td></tr></table></div><div class='clear'></div></div>";

function DisplayView(viewId)
{
    alert(viewId);
}
// get view count string end

// show city info
function ShowDesc(desc)
{
    $get("eleInfo").innerHTML = desc;
}

// show city info end

function SendParamToSearch(keywords)
{
    window.location.href = 'Search.aspx?keywords='+keywords;
}

// Search module
function SelectViewByKeyword(pageIndex)
{
    ret = 0;
    var pageSize = 10;
    var keywords;
    try
    {
        keywords = $get("txtSearch").value;
        WSLogin.SelectViewByKeyword(keywords,pageSize,pageIndex,OnCompleteSelectViewByKeyword, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectViewByKeyword(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            $get("searchPlace").innerHTML = ReplaceKeywords(keywords,args.SearchViews);
            var maxPageIndex = parseInt(args.SearchViewsCount/pageSize) + 1;
            $get("placeCount").innerHTML = args.SearchViewsCount+ "个地点";
            $get("placeH1").innerHTML = String.format("地点({0})...", args.SearchViewsCount);
            showDataGridFooter(maxPageIndex,pageIndex,"searchPlaceFooter",10, "SelectViewByKeyword");
        }
    }
    
    return ret;
}

function SelectEventHByKeyword(pageIndex)
{
    ret = 0;
    var pageSize = 10;
    var keywords;
    try
    {
        keywords = $get("txtSearch").value;
        WSLogin.SelectEventHByKeyword(keywords,pageSize,pageIndex,OnCompleteSelectEventHByKeyword, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectEventHByKeyword(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            $get("eventHeadDiv").innerHTML = ReplaceKeywords(keywords,args.SearchEventHs);
            var maxPageIndex = parseInt(args.SearchEventHsCount/pageSize) + 1;
            $get("ehCount").innerHTML = args.SearchEventHsCount+ "个活动";
            $get("ehH1").innerHTML = String.format("活动({0})...", args.SearchEventHsCount);
            showDataGridFooter(maxPageIndex,pageIndex,"eventHFooter",10, "SelectEventHByKeyword");
        }
    }
    
    return ret;
}

function ReplaceKeywords(keywords, searchViews)
{
    var ret = searchViews;
    var keywordList = keywords.split(' ');
    for(var i=0;i<keywordList.length;i++)
    {
        var re = new RegExp(keywordList[i],'g');
        ret = ret.replace(re,String.format('<font class="redfont">{0}</font>',keywordList[i]));
    }
    
    return ret;
}

function DataGrid(dataBinder)
{
    this.BindData = dataBinder;
 
    // footer template

}

function showDataGridFooter(maxPageIndex, currentPageIndex, footerDiv,footerPageSize, DataGridMethodName)
{
    var maxFooterPageIndex = parseInt(maxPageIndex/footerPageSize) + 1;
    var currentFooterPageIndex = parseInt((currentPageIndex-1)/footerPageSize) + 1;

    var previousPageTemplate = '<a id="prePage" href="#" onclick="{0}({1});return false">上一页</a>';
    var nextPageTemplate = '<a id="nextPage" href="#" onclick="{0}({1});return false">下一页</a>';
    var notSelectedTemplate = '<a href="#" onclick="{0}({1});return false">{2}</a>';
    var selectedTemplate = '<font class="nowpage">{0}</font>';
    
    //data grid footer div
    var pageIndex = $get(footerDiv);
    pageIndex.innerHTML = '';
    
    // 添加上一页
    if(currentPageIndex>1)
    {
        pageIndex.innerHTML += 
            String.format(previousPageTemplate,DataGridMethodName,currentPageIndex-1);
    }

    // 添加中间的选项
    for(var i = (currentFooterPageIndex-1)*footerPageSize+1; i<= currentFooterPageIndex*footerPageSize; i++)
    {
        if(i==maxPageIndex+1)
        {
            break;
        }
        if(currentPageIndex==i)
        {
            pageIndex.innerHTML += String.format(selectedTemplate,i);
        }
        else
        {
            pageIndex.innerHTML += 
                String.format(notSelectedTemplate,DataGridMethodName,i,i);
        }
    }
    
    //添加下一页
    if(currentPageIndex<maxPageIndex)
    {
        pageIndex.innerHTML += 
            String.format(nextPageTemplate,DataGridMethodName,currentPageIndex+1);
    }
}

//////////////index.page tuny event
function SelectTunyEventH()
{
    try
    {
        WSLogin.SelectTunyEventH(OnCompleteSelectTunyEventH, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectTunyEventH(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            $get("divEventItem").innerHTML = args.RetString;
        }
    }
}

//delEventDetail
function delEventDetail(ehId, edId)
{
    ret = false;
    try
    {
        WSLogin.DeleteEdAndEvs(edId, OnCompleteDeleteEdAndEvs, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteDeleteEdAndEvs(args)
    {
        if(!args.Ret)
        {
            alert("删除失败");
        }
        else
        {
            GetTrips(ehId);
        }
    }
    
    return ret;
}
// end delEventDetail

//delEventDetailByDayNum
function delEventDetailByDayNum(ehId,dayNumber)
{
    ret = false;
    try
    {
        WSLogin.DeleteEventDetailByDayNum(dayNumber, OnCompleteDeleteEventDetailByDayNum, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteDeleteEventDetailByDayNum(args)
    {
        if(!args.Ret)
        {
            alert("删除失败");
        }
        else
        {
            GetTrips(ehId);
        }
    }
    
    return ret;
}
//end delEventDetailByDayNum

//delEventView
function delEventViewForTripPlan(ehId,evId)
{
    ret = false;
    try
    {
        var eventView = {"Id":evId};
        
        WSLogin.DeleteEventView(eventView, OnCompleteDeleteEventView, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteDeleteEventView(args)
    {
        if(!args.Ret)
        {
            alert("删除失败");
        }
        else
        {
            GetTrips(ehId);
        }
    }
    
    return ret;
}
//end delEventView

//delEventView
function DeleteEventH(ehId)
{
    ret = false;
    try
    {
        WSLogin.DeleteEventH(ehId, OnCompleteDeleteEventH, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteDeleteEventH(args)
    {
        if(!args.Ret)
        {

        }
        else
        {
            if($get("allEvent"))
            {
                SelectAllEH(0,"allEvent");
            }
        }
    }
    
    return ret;
}
//end delEventView

// fill user info

// Update user profile for reg
function SetUserInfo()
{
    try
    {
        WSLogin.GetUserInfo(OnCompleteGetUserInfo, OnTimeOut, OnError);
     }
     catch(ex)
     {
        alert(ex.message);
     }
     
    function OnCompleteGetUserInfo(args)
    {
        if(!args)
        {
            alert("failed");
        }
        else
        {
            if(args.Ret)
            {
//            var userProfile = {"Gender":gender,"BirthYear":birthYear,"BirthMonth":birthMonth,"BirthDay":birthDay,
//                                   "HomeProvinceId":listHomeProvince,"HomeCityId":listHomeCity,"ProvinceID":listProvince,
//                                   "CityID":listCity,"MobilePhone":mobilePhone,"QQ":qq,"MSN":msn};
                var userProfile = args.ObjList[0];
                if(userProfile.Gender == 'M')
                {
                    $get('male').checked = true;
                }
                else if(userProfile.Gender == 'F')
                {
                    $get('female').checked = true;
                }
                else
                {
                    //
                }
                
                SetSelectItemByValue($get('birthYear'),userProfile.BirthYear);
                $get('birthYear').onchange();
                SetSelectItemByValue($get('birthMonth'),userProfile.BirthMonth);
                $get('birthMonth').onchange();
                SetSelectItemByValue($get('birthDay'),userProfile.BirthDay);
                
                SetSelectItemByValue($get('listHomeProvince'),userProfile.HomeProvinceId);
                SelectCityByProvinceIdAndDefaultCityId($get('listHomeProvince').value,'listHomeCity',userProfile.HomeCityId);
                
                SetSelectItemByValue($get('listProvince'),userProfile.ProvinceID);
                SelectCityByProvinceIdAndDefaultCityId($get('listProvince').value,'listCity',userProfile.CityID);
                
                $get('mobilePhone').value = userProfile.MobilePhone;
                $get('qq').value = userProfile.QQ;
                $get('msn').value = userProfile.MSN;
            }
        }
    }
}

// fill user info end

function SelectCityByProvinceIdAndDefaultCityId(pId, listCityId, selectedCityId)
{
    try
    {
        WSLogin.SelectCityByProvinceId(pId,OnCompleteGetCity, OnTimeOut, OnError);
     }
     catch(ex)
     {
        alert(ex.message);
     }
     
    function OnCompleteGetCity(args)
    {
        var listCity = document.getElementById(listCityId);
        
        listCity.options.length=0;
        for(var i=0;i<args.ObjList.length;i++)
        {
            var option = new Option(args.ObjList[i].Name,args.ObjList[i].ID);
            if(option.value==selectedCityId)
            {
                option.selected = true;
            }
            listCity.add(option);
        }
        
    }
}

function SetSelectItemByValue(objSelect,objItemValue)
{
     for(var i=0;i<objSelect.options.length;i++)
     {
         if(objSelect.options[i].value == objItemValue)
         {
             objSelect.options[i].selected = true;
             break;
         }
     }     
}

function UpdateUserProfileField(userProfile, upHandle, failupHandle)
{
    try
    {
        WSLogin.UpdateUserProfile(userProfile,OnCompleteUpdateUserProfile, OnTimeOut, OnError);
     }
     catch(ex)
     {
        alert(ex.message);
     }
     
    function OnCompleteUpdateUserProfile(args)
    {
        if(!args)
        {
            failupHandle();
        }
        else
        {
            upHandle();
        }
    }
}

function AttendEvent()
{
    try
    {
        requestParam = GetRequestParam();
        if(requestParam)
        {
            WSLogin.AttendEvent(requestParam.ehId,OnCompleteAttendEvent, OnTimeOut, OnError);
        }
     }
     catch(ex)
     {
        alert(ex.message);
     }
     
    function OnCompleteAttendEvent(args)
    {
        if(args)
        {
            if(args.Ret)
            { 
                GetAttendUserListByEhId();
                var adCount = parseInt($get("lblAttendCount").innerHTML);
                $get("lblAttendCount").innerHTML = adCount+1;
            }
            else
            {
                alert("请先登陆");
            }
            window.location.href=getSubstr(window.location.href,"#") +"#attendUserList";
        }
        else
        {
            alert("系统错误");
        }
    }
}

function PayAttentionToEvent()
{
    try
    {
        requestParam = GetRequestParam();
        if(requestParam)
        {
            WSLogin.PayAttentionToEvent(requestParam.ehId,OnCompletePayAttentionToEvent, OnTimeOut, OnError);
        }
     }
     catch(ex)
     {
        alert(ex.message);
     }
     
    function OnCompletePayAttentionToEvent(args)
    {
        if(args)
        {
            if(args.Ret)
            {
                GetAttentionUserListByEhId();
                var adCount = parseInt($get("lblAttentionCount").innerHTML);
                $get("lblAttentionCount").innerHTML = adCount+1;
            }
            else
            {
                alert("请先登陆");
            }
            window.location.href=getSubstr(window.location.href,"#") + "#attentionUserList";
        }
        else
        {
            alert("系统错误");
        }
    }
}

function GetDonkeyList()
{
    try
    {
        WSLogin.GetDonkeyList(OnCompleteGetDonkeyList, OnTimeOut, OnError);
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteGetDonkeyList(args)
    {
        if(args)
        {
            if(args.Ret)
            {
                $get("donkeyList").innerHTML = args.RetString;
            }
            else
            {
                alert("获取失败");
            }
        }
        else
        {
            alert("获取失败");
        }
    }
}

function GetAttendUserListByEhId()
{
    try
    {
        if(!requestParam)
        {
            requestParam = GetRequestParam();
        }
        
        WSLogin.SelectAttendUserListByEhId(requestParam.ehId,OnCompleteSelectAttendUserListByEhId, OnTimeOut, OnError);
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteSelectAttendUserListByEhId(args)
    {
        if(args)
        {
            if(args.Ret)
            {
                $get("attendUserList").innerHTML = args.RetString;
                if(args.IsCurrentUserAttend)
                {
                    isAttend = true;
                    $get("btnAttend").style.display = "none";
                    $get("btnAttention").style.display = "none";
                    $get("btnQuit").style.display = "block";
                }
                else
                {
                    $get("btnQuit").style.display = "none";
                }
            }
            else
            {
                alert("获取失败");
            }
        }
        else
        {
            alert("获取失败");
        }
    }
}

function GetAttentionUserListByEhId()
{
    try
    {
        if(!requestParam)
        {
            requestParam = GetRequestParam();
        }
        
        WSLogin.SelectAttentionUserListByEhId(requestParam.ehId,OnCompleteSelectAttentionUserListByEhId, OnTimeOut, OnError);
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteSelectAttentionUserListByEhId(args)
    {
        if(args)
        {
            if(args.Ret)
            {
                $get("attentionUserList").innerHTML = args.RetString;
                if(isAttend)
                {
                    $get("btnAttend").style.display = "none";
                    $get("btnAttention").style.display = "none";
                    $get("btnQuit").style.display = "block";
                    $get("btnCancelAttention").style.display = "none";
                }
                else if(args.IsCurrentUserAttention)
                {
                    
                    $get("btnAttention").style.display = "none";
                    $get("btnCancelAttention").style.display = "block";
                    $get("btnQuit").style.display = "none";
                }
                else
                {
                    $get("btnAttend").style.display = "block";
                    $get("btnAttention").style.display = "block";
                    $get("btnQuit").style.display = "none";
                    $get("btnCancelAttention").style.display = "none";
                }
            }
            else
            {
                alert("获取失败");
            }
        }
        else
        {
            alert("获取失败");
        }
    }
}

function QuitEvent()
{
    try
    {
        if(!requestParam)
        {
            requestParam = GetRequestParam();
        }
        
        WSLogin.QuitEvent(requestParam.ehId,OnCompleteQuitEvent, OnTimeOut, OnError);
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteQuitEvent(args)
    {
        if(args)
        {
            if(args.Ret)
            {
                isAttend = false;
                GetAttendUserListByEhId();
                GetAttentionUserListByEhId();
                var adCount = parseInt($get("lblAttendCount").innerHTML);
                $get("lblAttendCount").innerHTML = adCount-1;
                var adCount = parseInt($get("lblAttentionCount").innerHTML);
                $get("lblAttentionCount").innerHTML = adCount+1;
            }
            else
            {
                alert("退出失败");
            }
        }
        else
        {
            alert("系统错误");
        }
    }
}

function CancelAttentionEvent()
{
    try
    {
        if(!requestParam)
        {
            requestParam = GetRequestParam();
        }
        
        WSLogin.CancelAttentionEvent(requestParam.ehId,OnCompleteCancelAttentionEvent, OnTimeOut, OnError);
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteCancelAttentionEvent(args)
    {
        if(args)
        {
            if(args.Ret)
            {
                GetAttendUserListByEhId();
                GetAttentionUserListByEhId();
                var adCount = parseInt($get("lblAttentionCount").innerHTML);
                $get("lblAttentionCount").innerHTML = adCount-1;
            }
            else
            {
                alert("取消失败");
            }
        }
        else
        {
            alert("系统错误");
        }
    }
}

function FillAlbumNames()
{
    try
    {
        WSLogin.SelectByUserId(OnCompleteSelectByUserId, OnTimeOut, OnError);
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteSelectByUserId(args)
    {
        if(args)
        {
            if(args.Ret)
            {
                var listAlbum = $get("userAlbum");
                listAlbum.options.length = 0;
                listAlbum.add(new Option("--选择相册--",0));
                for(var i=0;i<args.ObjList.length;i++)
                {
                    var option = new Option(args.ObjList[i].Album_name,args.ObjList[i].Id);
                    listAlbum.add(option);
                }
            }
            else
            {
            
            }
        }
        else
        {
            alert("系统错误");
        }
    }
}

function AddAlbum()
{
    try
    {
        if(regularExpressionValid('txtAlbumName',NICKNAME_REGULAR_EXPRESSION,'txtError','相册名称输入有误!'))
        {
            WSLogin.AddAlbum($get("txtAlbumName").value, OnCompleteAddAlbum, OnTimeOut, OnError);
        }
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteAddAlbum(args)
    {
        if(args)
        {
            FillAlbumNames();
        }
        else
        {
            IsLogin();
        }
    }
}

function AddUserPics()
{
    try
    {
        if($get("userAlbum").selectedIndex==0)
        {
            alert("请选择相册名称");
            return;
        }
        
        if(!$get("txtTitle").value)
        {
            alert("请输入标题");
            return;
        }
        
        if(regularExpressionValid('txtTitle',NICKNAME_REGULAR_EXPRESSION,'txtError','标题输入有误!') &&
            regularExpressionValid('txtMemo',NICKNAME_REGULAR_EXPRESSION,'txtError','说明输入有误!')
         )
        {
            var userPic = 
                {
                    "Album_id":$get("userAlbum").value,
                    "Album_name":$get("userAlbum").options[$get("userAlbum").selectedIndex].text,
                    "Title":$get("txtTitle").value,
                    "Memo":$get("txtMemo").innerHTML,
                    "Note":picNotesList.toString(),
                    "Pic_url":$get("txtPic").value
                 };
            WSLogin.AddUserPics(userPic, OnCompleteAddUserPics, OnTimeOut, OnError);
        }
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteAddUserPics(args)
    {
        if(args)
        {
            $get("userAlbum").value = '';
            picNotesList.length=0;
            $get("userAlbum").selectedIndex=0;
            form1.submit();
        }
        else
        {
            alert("添加失败！");
        }
    }
}

function GetParentRequestParam()
{ 
    var request = new Object();
    var id=window.parent.window.location.search.substring(1); 
    if(id=="")
        return null;
    var tmp=id.split("&"); 
    var tmp_l=tmp.length; 

    for(var i=0;i<tmp_l;i++)
    { 
        var tmp2=tmp[i]; 
        tmp2=tmp2.split("="); 
        request[tmp2[0]] = tmp2[1];
    } 
    return request; 
} 

function SelectAlbumListByOwner()
{
    try
    {
        if(!requestParam)
        {
            requestParam = GetParentRequestParam();
        }
        
        WSLogin.SelectAlbumListByOwner(requestParam.uid, OnCompleteSelectAlbumListByOwner, OnTimeOut, OnError);
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteSelectAlbumListByOwner(args)
    {
        if(args)
        {
            if(args.RetString)
                $get("albumBoxList").innerHTML = args.RetString;
                $get("ListCount").innerHTML = args.ListCount;
                $get("PicCount").innerHTML = args.PicCount;
        }
        else
        {
            alert("系统错误！");
        }
    }
}

function SelectByAlbumId(pageIndex)
{
    var pageSize = 1;
    try
    {
        var uid = "";
        var albumId = "";

        uid = GetParentRequestParam().uid;
        var reqParam = GetRequestParam();
        if(reqParam)
        {
            albumId = reqParam.albumId;
        }
        else
        {
            albumId = 0;
        }
        WSLogin.SelectByAlbumId(uid,albumId,pageSize,pageIndex, OnCompleteSelectByAlbumId, OnTimeOut, OnError);
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteSelectByAlbumId(args)
    {
        if(args)
        {
            if(args.RetString)
            {
                $get("divPics").innerHTML = args.RetString;
                $get("lblAlbumName").innerHTML = args.Str1;
                currentEleId = args.Str2;
                showDataGridFooter(args.ListCount,pageIndex,"divPicsFooter",pageSize, "SelectByAlbumId");
                SelectPicLeaveWord(1);
            }
        }
        else
        {
            alert("系统错误！");
        }
    }
}

function SelectPicLeaveWord(pageIndex)
{
    var pageSize = 5;
    try
    {
        WSLogin.SelectLeaveWordByEleId(currentEleId,"pic",pageSize,pageIndex, OnCompleteSelectPicLeaveWord, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectPicLeaveWord(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            var delComment = '';
            
            $get("EHComment").innerHTML = '';
            for(var i=0;i<args.LeaveWords.length;i++)
            {
                var lv = args.LeaveWords[i];
                // if user login ,it can delete the comment
                if(args.IsLogin)
                {
                    delComment = String.format("<a href='#' onclick='delLeaveword({0},\"{1}\");return false;'>删除</a>",lv.Id,"pic");
                }
                $get("EHComment").innerHTML += String.format(commentTemplate,lv.Id,lv.Pic,delComment,lv.Keyin_date,lv.Uid,lv.Nick_Name,lv.LeaveWords,lv.Uid);
            }
            
            showDataGridFooter(args.MaxPageIndex,pageIndex,"EHCommentFooter",pageSize, "SelectPicLeaveWord");

            $get("leaveWordCount").innerHTML = args.ObjectCount;
            
        }
    }
}
var currentEleId = "";
function InsertLeaveWordsForPic()
{
    ret = false;
    var leaveWord;
    try
    {
        leaveWord = {"LeaveWords":$get("LeaveWords").value,"ElementId":currentEleId,"ElementType":"pic"};
        WSLogin.InsertLeaveWords(leaveWord, OnCompleteInsertLeaveWords, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteInsertLeaveWords(args)
    {
        if(!args.Ret)
        {
            if(!args.IsLogin)
            {
                alert("请登陆后留言");
            }
            else
            {
                alert("失败");
            }
        }
        else
        {
            var searchPicLeaveWordDataGrid = new DataGrid(SelectPicLeaveWord);
            searchPicLeaveWordDataGrid.BindData(1);
//            var lv = args.LeaveWords[0];
//            $get("EHComment").innerHTML += String.format(commentTemplate,lv.Id,lv.Pic,"<a href=''>删除</a>",lv.Keyin_date,lv.Uid,lv.Nick_Name,lv.LeaveWords);
        }
    }
    
    return ret;
}

var picNotesList = new Array();
function addPicNote()
{
    var txtNote = $get("txtNotes");
    picNotesList.push(txtNote.value);
    txtNote.value="";
    showPicNotes();
}
function delPicNote(str)
{
    picNotesList = picNotesList.delStr(str);
    showPicNotes();
}

function showPicNotes()
{
    var picNotesTemplate = "<li>{0} <img src='images/ico_close.gif' onclick='delPicNote(\"{1}\")' /></li>"
    var listPicNotes = $get("listPicNotes");
    listPicNotes.innerHTML = "";
    for(var i=0;i<picNotesList.length;i++)
    {
        listPicNotes.innerHTML += String.format(picNotesTemplate, picNotesList[i],picNotesList[i]);
    }
    
}


function InsertBlog()
{
    var blog;
    try
    {
        if(checkBlogEnter())
        {
            blog = {"Blog_title":$get("txtTitle").value,"Blog_type":getRadioValue("blogTypeList"),
                "Blog_note":picNotesList.toString(),"Blog_content":$get("txtContent").value};
            WSLogin.AddBlog(blog, OnCompleteAddBlog, OnTimeOut, OnError);
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteAddBlog(args)
    {
        if(!args.Ret)
        {
            if(!args.IsLogin)
            {
                alert("请登陆后添加文章");
            }
            else
            {
                alert("添加文章失败");
            }
        }
        else
        {
            window.location.href = "TFProfileBlog.aspx";
        }
    }
}

function UpdateBlog()
{
    var blog;
    try
    {
        if(checkBlogEnter())
        {
            blog = {"ID":GetRequestParam().blogId,"Blog_title":$get("txtTitle").value,"Blog_type":getRadioValue("blogTypeList"),
                "Blog_note":picNotesList.toString(),"Blog_content":$get("txtContent").value};
            WSLogin.UpdateBlog(blog, OnCompleteUpdateBlog, OnTimeOut, OnError);
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteUpdateBlog(args)
    {
        if(!args.Ret)
        {
            if(!args.IsLogin)
            {
                alert("请登陆后更改文章");
            }
            else if(args.RegResult == 1)
            {
                alert("只能更改自己发布的文章");
            }
            else
            {
                alert("更改文章失败");
            }
        }
        else
        {
            window.location.href = "TFProfileBlog.aspx";
        }
    }
}

function getRadioValue(divId)
{
    var btl = document.getElementById(divId);
    var ret = "";
    for(var i=0;i<btl.childNodes.length;i++)
    {
        var node = btl.childNodes[i];
        if(node.type=="radio" && node.checked)
        {
            ret = node.value;
        }
     }
     
     return ret;
}
function checkBlogEnter()
{
    if(!$get("txtTitle").value)
    {
        alert("请填写文章标题");
        return false;
    }
    if(!$get("txtContent").value)
    {
        alert("请填写文章内容");
        return false;
    } 
    
    return (regularExpressionValid('txtTitle',NICKNAME_REGULAR_EXPRESSION,'txtError','标题输入有误!') /*&&
            regularExpressionValid('txtContent',EVE_MEMO_REGULAR_EXPRESSION,'txtError','内容输入有误!')*/
         );
}
function InsertBlogTmp()
{
    ret = false;
    var blog;
    try
    {
        if(checkBlogEnter())
        {
            blog = {"Blog_title":$get("txtTitle").value,"Blog_type":getRadioValue("blogTypeList"),
                "Blog_note":picNotesList.toString(),"Blog_content":$get("txtContent").value};
            WSLogin.AddTmpBlog(blog, OnCompleteAddTmpBlog, OnTimeOut, OnError);
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteAddTmpBlog(args)
    {
        if(!args.Ret)
        {
            if(!args.IsLogin)
            {
                alert("请登陆后添加草稿");
            }
            else
            {
                alert("添加草稿失败");
            }
        }
        else
        {
            window.location.href = "TFProfileBlogDraft.aspx";
        }
    }
    
    return ret;
}

function UpdateBlogTmp()
{
    var blog;
    try
    {
        if(checkBlogEnter())
        {
            blog = {"ID":GetRequestParam().tmpBlogId,"Blog_title":$get("txtTitle").value,"Blog_type":getRadioValue("blogTypeList"),
                "Blog_note":picNotesList.toString(),"Blog_content":$get("txtContent").value};
            WSLogin.UpdateBlogTmp(blog, OnCompleteUpdateBlogTmp, OnTimeOut, OnError);
        }
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteUpdateBlogTmp(args)
    {
        if(!args.Ret)
        {
            if(!args.IsLogin)
            {
                alert("请登陆后更改草稿");
            }
            else if(args.RegResult == 1)
            {
                alert("只能更改自己发布的草稿");
            }
            else
            {
                alert("更改草稿失败");
            }
        }
        else
        {
            window.location.href = "TFProfileBlogDraft.aspx";
        }
    }
}

function SelectBlogByOwnerId(pageIndex)
{
    var pageSize = 5;
    try
    {
        var uid = GetParentRequestParam().uid;
        WSLogin.SelectBlogByOwnerId(uid,pageSize,pageIndex, OnCompleteSelectBlogByOwnerId, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectBlogByOwnerId(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            $get("blogList").innerHTML = args.RetString;
            showDataGridFooter(args.ListCount,pageIndex,"blogListFooter",pageSize, "SelectBlogByOwnerId");
        }
    }
}

function SelectBlogTmpByOwnerId(pageIndex)
{
    var pageSize = 5;
    try
    {
        var uid = GetParentRequestParam().uid;
        WSLogin.SelectBlogTmpByOwnerId(uid,pageSize,pageIndex, OnCompleteSelectBlogTmpByOwnerId, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectBlogTmpByOwnerId(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            $get("tmpBlogList").innerHTML = args.RetString;
            showDataGridFooter(args.ListCount,pageIndex,"tmpBlogListFooter",pageSize, "SelectBlogTmpByOwnerId");
        }
    }
}

function SelectSingleBlogByOwnerId()
{
    var pageSize = 1;
    try
    {
        var uid = GetParentRequestParam().uid;
        var blogId = GetRequestParam().blogId;
        WSLogin.SelectSingleBlogByOwnerId(uid,blogId, OnCompleteSelectSingleBlogByOwnerId, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectSingleBlogByOwnerId(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            $get("blogList").innerHTML = args.RetString;
            currentEleId = args.Str1;
            $get("blogListFooter").innerHTML = args.Str2;
            SelectBlogLeaveWord(1);
        }
    }
}

function InsertLeaveWordsForBlog()
{
    ret = false;
    var leaveWord;
    try
    {
        leaveWord = {"LeaveWords":$get("LeaveWords").value,"ElementId":currentEleId,"ElementType":"blg"};
        WSLogin.InsertLeaveWords(leaveWord, OnCompleteInsertLeaveWordsForBlog, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteInsertLeaveWordsForBlog(args)
    {
        if(!args.Ret)
        {
            if(!args.IsLogin)
            {
                alert("请登陆后留言");
            }
            else
            {
                alert("失败");
            }
        }
        else
        {
            UpdateBlogCommentCount(1);
            var searchBlogLeaveWordDataGrid = new DataGrid(SelectBlogLeaveWord);
            searchBlogLeaveWordDataGrid.BindData(1);
//            var lv = args.LeaveWords[0];
//            $get("EHComment").innerHTML += String.format(commentTemplate,lv.Id,lv.Pic,"<a href=''>删除</a>",lv.Keyin_date,lv.Uid,lv.Nick_Name,lv.LeaveWords);
        }
    }
    
    return ret;
}

function UpdateBlogReaderCount(number)
{
    ret = false;
    if(!GetRequestParam())
        return false;
    var blogId = GetRequestParam().blogId;
    try
    {
        WSLogin.UpdateBlogReaderCount(blogId,number, OnCompleteUpdateBlogReaderCount, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteUpdateBlogReaderCount(args)
    {
        if(!args.Ret)
        {
           
        }
        else
        {
            if($get("readerCount"))
            {
                $get("readerCount").innerHTML = parseInt($get("readerCount").innerHTML) + number;
            }
        }
    }
    
    return ret;
}

function UpdateBlogCommentCount(number)
{
    ret = false;
    var blogId = GetRequestParam().blogId;
    try
    {
        WSLogin.UpdateBlogCommentCount(blogId,number, OnCompleteUpdateBlogCommentCount, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteUpdateBlogCommentCount(args)
    {
        if(!args.Ret)
        {
           
        }
        else
        {
            if(number<0)
            {
                SelectBlogLeaveWord(1);
            }
            if(number>0)
            {
                
            }
            
            if($get("commentCount"))
            {
                var commentCont =  parseInt($get("commentCount").innerHTML) + number;
                if(commentCont<0)
                {
                    commentCont = 0;
                }
                $get("commentCount").innerHTML = commentCont;
            }
        }
    }
    
    return ret;
}

function SelectBlogLeaveWord(pageIndex)
{
    var pageSize = 5;
    try
    {
        WSLogin.SelectLeaveWordByEleId(currentEleId,"blg",pageSize,pageIndex, OnCompleteSelectBlogLeaveWord, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectBlogLeaveWord(args)
    {
        if(!args.Ret)
        {
            alert("失败");
        }
        else
        {
            var delComment = '';
            
            $get("EHComment").innerHTML = '';
            for(var i=0;i<args.LeaveWords.length;i++)
            {
                var lv = args.LeaveWords[i];
                // if user login ,it can delete the comment
                if(args.IsLogin)
                {
                    delComment = String.format("<a href='#' onclick='delLeaveword({0},\"{1}\");return false;'>删除</a>",lv.Id,"blg");
                }
                $get("EHComment").innerHTML += String.format(commentTemplate,lv.Id,lv.Pic,delComment,lv.Keyin_date,lv.Uid,lv.Nick_Name,lv.LeaveWords,lv.Uid);
            }
            
            showDataGridFooter(args.MaxPageIndex,pageIndex,"EHCommentFooter",pageSize, "SelectBlogLeaveWord");

            $get("leaveWordCount").innerHTML = args.ObjectCount;
            
        }
    }
}

function delBlog(blogId)
{
    ret = false;
    try
    {
        WSLogin.DelBlog(blogId, OnCompleteDelBlog, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteDelBlog(args)
    {
        if(args)
        {
            if(!args.IsLogin)
            {
                alert("请登陆后删除");
            }
            else
            {
                if(args.RegResult==1)
                {
                    //delete successfully
                    SelectBlogByOwnerId(1);
                }
                else if(args.RegResult==2)
                {
                    alert("只有创建者可以删除");
                }
                else
                {
                    alert("删除失败,请联系管理员");
                }
            }
        }
        else
        {
            alert("系统错误");
        }
    }
    
    return ret;
}

function editBlog(blogId)
{
    try
    {
        WSLogin.IsLogin(OnCompleteIsLogin, OnTimeOut, OnError);
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteIsLogin(args)
    {
        if(args)
        {
            window.location.href = "TFProfileBlogNew.aspx?blogId=" + blogId;
        }
        else
        {
            alert("请先登陆");
        }
    }
}

function editTmpBlog(tmpBlogId)
{
    try
    {
        WSLogin.IsLogin(OnCompleteIsLogin, OnTimeOut, OnError);
    }
    catch(ex)
    {
        alert(ex.message);
    }
     
    function OnCompleteIsLogin(args)
    {
        if(args)
        {
            window.location.href = "TFProfileBlogNew.aspx?tmpBlogId=" + tmpBlogId;
        }
        else
        {
            alert("请先登陆");
        }
    }
}

function setRadioValue(divId, foundValue)
{
    var btl = document.getElementById(divId);

    for(var i=0;i<btl.childNodes.length;i++)
    {
        var node = btl.childNodes[i];
        if(node.type=="radio" && node.value == foundValue)
        {
             node.checked = true;
        }
     }

}

function fillBlog()
{
    if(!GetRequestParam())
    {
        return;
    }
    
    var blogId = GetRequestParam().blogId;
    try
    {
        WSLogin.SelectBlogById(blogId, OnCompleteSelectBlogById, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectBlogById(args)
    {
        if(args)
        {
            blog = {"Blog_title":$get("txtTitle").value,"Blog_type":getRadioValue("blogTypeList"),
                "Blog_note":picNotesList.toString(),"Blog_content":$get("txtContent").value};
                
            $get("txtTitle").value = args.Blog_title;
            $get("txtContent").value = args.Blog_content;
            setRadioValue("blogTypeList",args.Blog_type);

            picNotesList = args.Blog_note.split(",");
            showPicNotes();
        }
        else
        {
            alert("系统错误");
        }
    }
}

function fillBlogTmp()
{
    if(!GetRequestParam())
    {
        return;
    }
    
    var tmpBlogId = GetRequestParam().tmpBlogId;
    try
    {
        WSLogin.SelectBlogTmpById(tmpBlogId, OnCompleteSelectBlogTmpById, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectBlogTmpById(args)
    {
        if(args)
        {
            blog = {"Blog_title":$get("txtTitle").value,"Blog_type":getRadioValue("blogTypeList"),
                "Blog_note":picNotesList.toString(),"Blog_content":$get("txtContent").value};
                
            $get("txtTitle").value = args.Blog_title;
            $get("txtContent").value = args.Blog_content;
            setRadioValue("blogTypeList",args.Blog_type);

            picNotesList = args.Blog_note.split(",");
            showPicNotes();
        }
        else
        {
            alert("系统错误");
        }
    }
}

function publishBlog(tmpBlogId)
{
    try
    {
        WSLogin.PublicBlogTmp(tmpBlogId, OnCompletePublicBlogTmp, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompletePublicBlogTmp(args)
    {
        if(!args.Ret)
        {
            if(!args.IsLogin)
            {
                alert("请登陆后发布");
            }
            else if(args.RegResult == 1)
            {
                alert("只能发布自己的草稿");
            }
            else
            {
                alert("发布失败");
            }
        }
        else
        {
            window.location.href = "TFProfileBlog.aspx";
        }
    }
}

function SelectBlogTmpCountByOwnerId()
{
    try
    {
        WSLogin.SelectBlogTmpCountByOwnerId(OnCompleteSelectBlogTmpCountByOwnerId, OnTimeOut, OnError);
    }
    catch(err)
    {
        alert("有错误发生" + err.description);
    }

    function OnCompleteSelectBlogTmpCountByOwnerId(args)
    {
        if(args.Ret)
        {
            $get("linkDraft").style.display = "inline";
            $get("lblDraftCount").innerHTML = args.Str1;
        }
        else
        {
            $get("linkDraft").style.display = "none";
        }
        
    }
}